from backend.eform.models import  EformFile
from backend.eform.utils import checkCanEndorse, getCheckFunction
from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from rest_framework.decorators import action, api_view
from rest_framework.views import APIView
from rest_framework import viewsets,mixins
from rest_framework.response import Response
from .serializers import  EformFileSerializer
from django.contrib.auth.models import User
# from users.models import Profile
import datetime


# class IMTE(APIView):
    
#     def get(self,request,pk=False):
#         if not pk:
#             return Response({'err':'err'})
#         imte = Imte.objects.filter(imte_no=pk).first()
#         print(imte)
#         if not imte:
#             return Response({'err':'err'})
#         return Response(ImteSerializer(imte).data)
    
    # @action(methods=['get'],detail=False,url='getIMTEByWO')
    # def getIMTEByWO(self,request):
    #     wo = request.GET.get('wo',False)
    #     if not wo:
    #         return Response({
    #             'err':'WO is missing',
    #             'ack':False,
    #         })
    #     wo_imte = WorkOrderList_Imte.objects.filter(workOrderList__cews_w_order=wo)
    #     imte = [{
    #         'imte_no':x.imte,
    #         'imte_type':x.imte_type,
    #         'due_date':x.due_date
    #     } for x in wo_imte]
    #     return Response(imte)

def getIMTEByWO(request):
    wo = request.GET.get('wo',False)
    if not wo:
        return JsonResponse({
            'err':'WO is missing',
            'ack':False,
        })
    # wo_imte = WorkOrderList_Imte.objects.filter(workOrderList__cews_w_order=wo)
    ## FIXME
    
    wo_imte = []
    
    imte = [{
        'imte_no':x.imte,
        'imte_type':x.imte_type,
        'due_date':x.due_date
    } for x in wo_imte]
    return JsonResponse(imte)

def setWorkOrderIMTE(request,wo_id):
    imte_no = request.POST.get('imte_no',False)
    due_date = request.POST.get('due_date',False)
    imte_type = request.POST.get('imte_type',False)
    if not due_date:
        return JsonResponse({
            'err':'due_date is missing'
        })

    if not imte_no:
        return JsonResponse({
            'err':'imte_no is missing'
        })
    
    ## check due_date
    try:
        ddd = datetime.datetime.strptime(due_date,'%Y-%m-%d')
    except Exception as ex:
        return JsonResponse({
            'err':f'Incorrect due_date format ({due_date})',
            'ack':False
        })
    now = datetime.datetime.now()
    if ddd < now:
        return JsonResponse({
            'err':f'Device: {imte_no} is expired. ({due_date} < {now:%Y-%m-%d})',
            'ack':False
        })
    # print(imte_no)
    # imte = Imte.objects.filter(imte_no=imte_no).first()
    
    # FIXME
    # wo = WorkOrderList.objects.filter(pk=wo_id).first()
    wo = False
    
    if not wo:
        return JsonResponse({
            'err':'WO not found',
            'ack':False
        })

    ## CHECK IF EXIST
    ## FIXME
    #wo_imte = WorkOrderList_Imte.objects.filter(imte=imte_no, workOrderList= wo,due_date=ddd).first()
    wo_imte = False
    if wo_imte:
        return JsonResponse({
            'err':'IMTE Already Added',
            'ack':False
        })

    ## FIXME
    # try:
    #     wo_imte = WorkOrderList_Imte(imte=imte_no,imte_type=imte_type, workOrderList= wo,user=request.user,due_date=due_date)
    #     wo_imte.save()

    # except Exception as e:
    #     print(e)
    #     return JsonResponse({
    #         'ack':False,
    #         'err':'Error while saving'
    #     })

    return JsonResponse({
        'ack':True
    })

def deleteWorkOrderIMTE(request,wo_id):
    imte_no = request.POST.get('imte_no',False)
    print(request.POST)
    if not imte_no:
        return JsonResponse({
            'err':'imte_no is missing'
        })
    
    # FIXME
    wo = False
    # wo = WorkOrderList.objects.filter(pk=wo_id).first()
    
    if not wo:
        return JsonResponse({
            'err':'WO not found'
        })
    # FIXME
    # wo_imte = WorkOrderList_Imte.objects.filter(imte=imte_no, workOrderList= wo).first()
    # imte_type = wo_imte.imte_type
    # if wo_imte:
    #     wo_imte.delete()    
    #     return JsonResponse({
    #         'imte_type':imte_type,
    #         'ack':True
    #     })

    # if not wo_imte:
    #     return JsonResponse({
    #         'err':'WO_IMTE not found'
    #     })

@api_view(['POST'])
def getCheckUser(request):
    """
        Search user by base64 username, and check if uesr has permission of the submited check_state
        @params {String, base64} request.POST['username']
        @params {String} request.POST['check_state'], {endrose|verify} 
        return JsonResponse of {String} username, {int} user_id, {String} err, {bool} ack
    """
    print(request.POST)
    username_base64 = request.POST.get('username',False)
    check_state = request.POST.get('check_state',False)

    if not username_base64:
        return JsonResponse({
            'err':'Username is missing',
            'ack':False
        })

    if not check_state:
        return JsonResponse({
            'err':'check_state missing',
            'ack':False
        })

    ## decode username by base64
    # try:        
    #     username = base64.b64decode(username_base64).decode()
    # except:
    #     return JsonResponse({
    #         'err':'Incorrect username',
    #         'ack':False
    #     })

    # print(username)
    # user = User.objects.filter(username=username,is_active=True).first()
    
    # FIXME: add base 64 to profile
    
    # use qr code to checkin
    # print("username_base64", username_base64)
    # profiles = Profile.objects.filter(qrcode=username_base64)
    # print("profiles", profiles)
    # user=None
    # if profiles.exists():
    #     profile = profiles.get()
    #     users = User.objects.filter(profile=profile,is_active=True)
    #     if users.exists():
    #         user=users.first()
    # else:
    #     print("Cannot find QR code")

    # if user:
    #     checkFunction = getCheckFunction(check_state)

    #     if not checkFunction:
    #         return JsonResponse({
    #             'err':'Incorrect check_state',
    #             'ack':False
    #         })

    #     has_permission = checkFunction(user)

    #     if has_permission:
    #         return JsonResponse({
    #             'user_id':user.id,
    #             'username':user.username,
    #             'ack':True
    #         })
    #     else:
    #         return JsonResponse({
    #             'err':'User has insufficient permission',
    #             'ack':False
    #         })

    return JsonResponse({
        'err':'Username not found',
        'ack':False
    })


class EformFileViewSet(mixins.CreateModelMixin,
                   mixins.RetrieveModelMixin,
                   mixins.UpdateModelMixin,
                    mixins.DestroyModelMixin,
                   mixins.ListModelMixin,
                   viewsets.GenericViewSet):
    queryset = EformFile.objects.all()
    serializer_class = EformFileSerializer
    
        
    